package georah.map.tools
{

	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.geom.Point;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import georah.carto.SRS;

	/**
	 *
	 * @author yuanm
	 */
	public class PointQuery extends MapTool
	{
		private var _provider:IPointQueryProvider=null;

		private var _urlloader:URLLoader=new URLLoader();

		private var _urlrequest:URLRequest=null;

		public final function identify(pixel:Point):void
		{
			if (!map)
			{
				return;
			}

			toolInfo.update(map);
			_urlrequest=new URLRequest(toolInfo.featureInfoURL(pixel.x, pixel.y));
			_urlloader.load(_urlrequest);

			dispatchEvent(new PointQueryEvent(PointQueryEvent.IDENTIFY, SRS.fromPixelToWhere(pixel, map)));
		}

		override public function get keyboardLocked():Boolean
		{
			return false;
		}

		override public function get mouseLocked():Boolean
		{
			return false;
		}

		public final function get toolInfo():IPointQueryProvider
		{
			return _provider;
		}

		public final function set toolInfo(value:IPointQueryProvider):void
		{
			_provider=value;
		}

		virtual override protected function this_disableHandler(event:MapToolEvent):void
		{
			_urlloader.removeEventListener(Event.COMPLETE, urlLoader_completeHandler);
			_urlloader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, urlLoader_securityErrorHandler);
			_urlloader.removeEventListener(IOErrorEvent.IO_ERROR, urlLoader_ioErrorHandler);
			_urlloader.close();

			super.this_disableHandler(event);
		}

		virtual override protected function this_enableHandler(event:MapToolEvent):void
		{
			super.this_enableHandler(event);

			_urlloader.addEventListener(Event.COMPLETE, urlLoader_completeHandler);
			_urlloader.addEventListener(IOErrorEvent.IO_ERROR, urlLoader_ioErrorHandler);
			_urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, urlLoader_securityErrorHandler);
		}

		private final function urlLoader_completeHandler(event:Event):void
		{
			dispatchEvent(new PointQueryEvent(PointQueryEvent.IDENTIFY_RESULT, null, URLLoader(event.target).data, toolInfo.format));
		}

		private final function urlLoader_ioErrorHandler(event:IOErrorEvent):void
		{
			dispatchEvent(new PointQueryEvent(PointQueryEvent.IDENTIFY_FAULT, null, event.text));
		}

		private final function urlLoader_securityErrorHandler(event:SecurityErrorEvent):void
		{
			dispatchEvent(new PointQueryEvent(PointQueryEvent.IDENTIFY_FAULT, null, event.text));
		}

	}
}
